package ProjectoX;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Nivel extends Canvas implements KeyListener {

	private static final long serialVersionUID = 1L;
	protected Vector<Componente> misComponentes;
	protected Mario miMario;
	protected Mapa miMapa;
	protected int Alto;
	protected int Ancho;
	protected final int SPEED = 10;
	protected SpriteCache spriteCache;
	protected SoundCache soundCache;
	protected BufferStrategy strategy;
	protected long usedTime;
	protected JPanel panel;
	protected JLabel jLabel1;
	protected boolean gameEnded = false;
	protected boolean gameWined = false;
	final protected int ColumnasNivel = 10;
	final protected int AnchoC = 50;
	private BufferedImage fondo;
	
	public Nivel () {
		spriteCache = new SpriteCache();
		soundCache = new SoundCache();
		miMapa = new Mapa(this);
		Alto = miMapa.getPantalla().getAncho();
		Ancho = miMapa.getPantalla().getAlto();
		JFrame ventana = new JFrame("Mario");

		panel=new JPanel();

				setBounds(0,0,Ancho,Alto);
				panel.setPreferredSize(new Dimension(Alto,Ancho));
				panel.setLayout(null);
				panel.add(this);
				panel.setBackground(new Color(160, 170, 255));
				ventana.getContentPane().add(panel);
				panel.setOpaque(false);



		ventana.setBounds(0,0,Alto,Ancho);
		ventana.setVisible(true);
		ventana.addWindowListener( new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
		ventana.setResizable(false);
		createBufferStrategy(2);
		strategy = getBufferStrategy();
		addKeyListener(this);
	    setIgnoreRepaint(true);
	    requestFocus();
	}

    public SoundCache getSoundCache() {
        return soundCache;
    }

	public void inicializarNivel() {
		misComponentes = new Vector<Componente> ();
		miMario = new Mario(this);
		for (int i = 0; i < miMapa.getComponentes().length; i++) {
			for (int j = 0; j < miMapa.getComponentes()[0].length; j++) {
				if (miMapa.getComponentes()[i][j] != null)
					misComponentes.add(miMapa.getComponentes()[i][j]);
			}
		}
		soundCache.loopSound("Sonidos/music0.midi");
	}


	public void ciclo() {
		usedTime=1000;
		inicializarNivel();
		while (isVisible() && !gameEnded && !gameWined) {
			long startTime = System.currentTimeMillis();
			actualizarNivel();
			controlarColisiones();
			paintWorld();
			usedTime = System.currentTimeMillis()-startTime;
			try {
				Thread.sleep(SPEED);
			}
			catch (InterruptedException e) {}
		}
		if (gameEnded) {
			getSoundCache().playSound("Sonidos/smw_death.wav");
			paintGameOver();
		}
		else paintGameWin();
	}

	public void gameOver() {
		gameEnded = true;
	}

	public void gameWiner() {
		gameWined = true;
	}


	public void actualizarNivel() {
			miMario.actuar();
	}

	public void controlarColisiones() {
        Rectangle playerBounds = miMario.getBounds();
        for (int m = 0; m < misComponentes.size(); m++) {
        	Componente Ca1 = (Componente) misComponentes.get(m);
        	Rectangle Cr1 = Ca1.getBounds();
        	if (Cr1.intersects(playerBounds))
        		miMario.colision(Ca1);
        }
	}

	public Mario getPersonaje() {
		return miMario;
	}

	public Mapa getMapa() {
		return miMapa;
	}

	@Override
	public void keyPressed(KeyEvent e) {
		miMario.teclaPresionada(e);
	}

	@Override
	public void keyReleased(KeyEvent e) {
		miMario.teclaSoltada(e);
	}

	@Override
	public void keyTyped(KeyEvent e) {

	}

    public BufferedImage loadImage(String nombre) {
        URL url=null;
        try {
        	url = getClass().getClassLoader().getResource(nombre);
        	return ImageIO.read(url);
        }
        catch (Exception e) {
        	System.out.println("No se pudo cargar la imagen " + nombre +" de "+url);
        	System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
        	System.exit(0);
        	return null;
        }
    }

    public void paintWorld() {
    	Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
    	
    	fondo = spriteCache.getSprite("Fondo/arctis2.jpg");
	    g.setPaint(new TexturePaint(fondo, new Rectangle(0,0,498,500)));
	    g.fillRect(0,0,getWidth(),getHeight());
    	
        g.fillRect(0,0,getWidth(),getHeight());
        panel.paint(g);
        if ((miMario.getPos().getX()>=320)&&(miMario.getPos().getX()<=5500)) {      //SE PINTA DE ESTA MANERA EN TODOS LOS CASOS MENOS CUANDO ESTAMOS POSICIONADOS
        	int ini = miMario.getPos().getX();	//AL PRINCIPIO O AL FINAL
            ini =(ini -320);
            int z = ini;
            ini = ini/AnchoC;
            if (miMario.getPos().getX() % AnchoC !=0)
            	ini++;
            int fin = ini + ColumnasNivel;
    		for (int i = ini; i < fin; i++) {
            	for (int j = 0; j < 10; j++) {
            		Componente C = (Componente) miMapa.getComponentes()[i][j];
            		if (C!= null) {
        				System.out.println("I "+i);
                		C.setLocalization(C.getPos().getX()-z);
            			C.paint(g);
            		}
            	}
            }
        }
        else 
        	if (miMario.getPos().getX()<320){
        		for (int i = 0; i < ColumnasNivel; i++) {  //UTILIZAMOS ESTA PARTE DEL CODIGO PARA PINTAR LA PANTALLA CUANDO 
        			for (int j = 0; j < 10; j++) {			//ESTAMOS AL PRINCIPIO DEL NIVEL
        				Componente C = (Componente) miMapa.getComponentes()[i][j];
        				if (C!= null) {
        					C.setLocalization(C.getPos().getX());
        					C.paint(g);
        				}
        			}
        		}
        	}
        	else {
        		for (int i = 90; i < ColumnasNivel; i++) {  //UTILIZAMOS ESTA PARTE DEL CODIGO PARA PINTAR LA PANTALLA CUANDO 
        			for (int j = 0; j < 10; j++) {			//ESTAMOS AL FINAL DEL NIVEL
        				Componente C = (Componente) miMapa.getComponentes()[i][j];
        				if (C!= null) {
        					C.setLocalization(C.getPos().getX());
        					C.paint(g);
        				}
        			}
        		}
        		
        	}
        miMario.paint(g);
        strategy.show();
	}

	public void paintGameOver() {
		Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
		g.setColor(Color.black);
        g.fillRect(0,0,getWidth(),getHeight());
		g.setColor(Color.white);
		g.setFont(new Font("ARIAL", Font.BOLD, 30));
		g.drawString("GAME OVER",Ancho/2-80,Alto/2);
		strategy.show();
  }
	
	
	public void paintGameWin() {
		Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
		g.setColor(Color.black);
        g.fillRect(0,0,getWidth(),getHeight());
		g.setColor(Color.white);
		g.setFont(new Font("ARIAL", Font.BOLD, 30));
		g.drawString("YOU WIN",Ancho/2-80,Alto/2);
		strategy.show();
  }	

    public SpriteCache getSpriteCache() {
    	return spriteCache;
    }

}
